<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Admin_Categories extends Admin_Controller {
	public function __construct()
	{
		parent::Admin_Controller();
		$this->load->helper('form');
		$this->lang->load('cirpho');
		$this->lang->load('categories');
		$this->load->model('cip_categories_m');
		$this->load->model('cip_servers_m');
		$this->template
			->append_metadata( css('cirpho.css', 'cirpho') )
			->set_partial('shortcuts', 'admin/partials/shortcuts');
		// Set the validation rules
		$this->load->library('form_validation');
		$this->validation_rules = array(
			array(
				'field' => 'name',
				'label' => lang('categories.title_label'),
				'rules' => 'trim|required|max_length[20]'
			),
			array(
				'field' => 'order',
				'label' => lang('cirpho_category_order_label'),
				'rules' => 'trim|numeric|max_length[20]'
			)
		);
		$this->form_validation->set_rules($this->validation_rules);
	}
	public function index()
	{
		$this->pyrocache->delete_all('modules_m');
		// Create pagination links
		$total_rows = $this->cip_categories_m->count_by('deleted', 0);
		$pagination = create_pagination('admin/cirpho/categories/index', $total_rows, NULL, 5);
		// Using this data, get the relevant results
		$categories = $this->cip_categories_m->where('deleted', 0)->order_by('order_number','asc')->limit($pagination['limit'])->get_all();
		$this->template
			->title($this->module_details['name'], lang('cirpho_category_list_title'))
			->set('categories', $categories)
			->set('pagination', $pagination)
			->build('admin/categories/index', $this->data);
	}
	/**
	 * Create method, creates a new category
	 * @access public
	 * @return void
	 */
	public function create()
	{
		
		// Validate the data
		if ($this->form_validation->run())
		{
			$id = $this->cip_categories_m->insert($_POST);
			$isSuccess = true;
			if($id){
				$servers = $this->cip_servers_m->get_all();
				if($servers && count($servers)){
					foreach ($servers as $server){
						
						$config['hostname'] = $server->domain_name;
						$config['username'] = $server->database_user;
						$config['password'] = $server->database_password;
						$config['database'] = $server->database_name;
						$config['dbdriver'] = "mysql";
						$config['dbprefix'] = "";
						$config['pconnect'] = FALSE;
						$config['db_debug'] = FALSE;
						$config['cache_on'] = FALSE;
						$config['cachedir'] = "";
						$config['char_set'] = "utf8";
						$config['dbcollat'] = "utf8_general_ci";
						$config['port'] 	= 3306;
						$this->client_db = $this->load->database($config, TRUE);
						
						$dataSet = array(
								'id' => $id,
								'name' => $_POST['name'],
								'order_number' => $_POST['order_number'],
						  		'slug'	=>url_title(strtolower(convert_accented_characters($_POST['name'])))  
						);
						
					    $this->client_db->insert('default_cip_categories', $dataSet);
					    
					    $e = $this->client_db->_error_message();
					    $aff = $this->client_db->affected_rows();
						if($aff < 1) {
							$isSuccess = false;
							//echo "Error";
							$this->cip_owners_m->delete($id);
							foreach ($servers as $server){
								$config['hostname'] = $server->domain_name;
								$config['username'] = $server->database_user;
								$config['password'] = $server->database_password;
								$config['database'] = $server->database_name;
								$config['dbdriver'] = "mysql";
								$config['dbprefix'] = "";
								$config['pconnect'] = FALSE;
								$config['db_debug'] = FALSE;
								$config['cache_on'] = FALSE;
								$config['cachedir'] = "";
								$config['char_set'] = "utf8";
								$config['dbcollat'] = "utf8_general_ci";
								$config['port'] 	= 3306;
								
								$this->client_db = $this->load->database($config, TRUE);

								$this->client_db->delete('default_cip_categories', array('id' => $id)); 
							}
							break;
						}
					}
				}else{
					$isSuccess = false;
				}
				$isSuccess ? $this->session->set_flashdata('success', sprintf( lang('cirpho_category_add_success'), $this->input->post('name')) )
				: $this->session->set_flashdata(array('error'=> lang('cat_add_error')));
			}
			redirect('admin/cirpho/categories');
		}
		
		// Loop through each validation rule
		foreach($this->validation_rules as $rule)
		{
			$category->{$rule['field']} = set_value($rule['field']);
		}
		// Render the view	
		$this->data->category =& $category;	
		$this->template->title($this->module_details['name'], lang('cat_create_title'))
						->build('admin/categories/form', $this->data);	
	}
	
	/**
	 * Edit method, edits an existing category
	 * @access public
	 * @param int id The ID of the category to edit 
	 * @return void
	 */
	public function edit($id = 0)
	{	
		// Get the category
		$category = $this->cip_categories_m->get($id);
		
		// ID specified?
		$category or redirect('admin/cirpho/categories/index');
		
		// Validate the results
		if ($this->form_validation->run())
		{				
			$updateResult = $this->cip_categories_m->update($id, $_POST);
			$isSuccess = true;
			if($updateResult){
				$servers = $this->cip_servers_m->get_all();
				
				if($servers && count($servers)){
					foreach ($servers as $server){
						
						$config['hostname'] = $server->domain_name;
						$config['username'] = $server->database_user;
						$config['password'] = $server->database_password;
						$config['database'] = $server->database_name;
						$config['dbdriver'] = "mysql";
						$config['dbprefix'] = "";
						$config['pconnect'] = FALSE;
						$config['db_debug'] = FALSE;
						$config['cache_on'] = FALSE;
						$config['cachedir'] = "";
						$config['char_set'] = "utf8";
						$config['dbcollat'] = "utf8_general_ci";
						$config['port'] 	= 3306;
						
						$this->client_db = $this->load->database($config, TRUE);
						
						$dataSet = array(
								'name' => $_POST['name'],
								'order_number'=> $_POST['order_number'],
						  		'slug'	=>url_title(strtolower(convert_accented_characters($_POST['name'])))  
						);
						
						$this->client_db->where('id', $id);
						$this->client_db->update('default_cip_categories', $dataSet);
					    
					    $e = $this->client_db->_error_message();
					    $aff = $this->client_db->affected_rows();
						
						if($aff < 1) {
							$isSuccess = false;
							//echo "Error";
							//echo $e;
							
							$oldDataSet = array(
								'name' => $category->name,
								'order_number' => $category->order_number,
						  		'slug'	=>url_title(strtolower(convert_accented_characters($category->name)))
							);

							$this->cip_categories_m->update($id, $oldDataSet);
						
							foreach ($servers as $server){
								$config['hostname'] = $server->domain_name;
								$config['username'] = $server->database_user;
								$config['password'] = $server->database_password;
								$config['database'] = $server->database_name;
								$config['dbdriver'] = "mysql";
								$config['dbprefix'] = "";
								$config['pconnect'] = FALSE;
								$config['db_debug'] = FALSE;
								$config['cache_on'] = FALSE;
								$config['cachedir'] = "";
								$config['char_set'] = "utf8";
								$config['dbcollat'] = "utf8_general_ci";
								$config['port'] 	= 3306;
								
								$this->client_db = $this->load->database($config, TRUE);

								$this->client_db->where('id', $id);
								$this->client_db->update('default_cip_categories', $oldDataSet); 
							}
							break;
						}
					}
				}
			}else{
				$isSuccess = false;
			}
			$isSuccess ? $this->session->set_flashdata('success', sprintf( lang('cat_edit_success'), $this->input->post('title')) )
				: $this->session->set_flashdata(array('error'=> lang('cat_edit_error')));
				
			redirect('admin/cirpho/categories/index');
		}
		
		// Loop through each rule
		foreach($this->validation_rules as $rule)
		{
			if($this->input->post($rule['field']) !== FALSE)
			{
				$category->{$rule['field']} = $this->input->post($rule['field']);
			}
		}

		// Render the view
		$this->data->category =& $category;
		$this->template->title($this->module_details['name'], sprintf(lang('cat_edit_title'), $category->title))
						->build('admin/categories/form', $this->data);
	}	

	/**
	 * Delete method, deletes an existing category (obvious isn't it?)
	 * @access public
	 * @param int id The ID of the category to edit 
	 * @return void
	 */
	public function delete($id = 0)
	{	
		
		if($this->input->post('btnAction') == 'save'){
			//print_r( $this->input->post('order'));
			$orders = $this->input->post('order_number');
			$isSuccess = true;
			foreach ($orders as $key=>$value){
				if(!$isSuccess){
					break;
				}
				$id = $key;
				$category = $this->cip_categories_m->get($id);
				$dataSet = array(
										'name' => $category->name,
										'order_number' => $value,
										'slug'	=>url_title(strtolower(convert_accented_characters($category->name))),
										'deleted' => 0
				);
				if($this->cip_categories_m->updateDelete($id, $dataSet))
				{
					$servers = $this->cip_servers_m->get_all();
				
					if($servers && count($servers)){
						foreach ($servers as $server){
				
							$config['hostname'] = $server->domain_name;
							$config['username'] = $server->database_user;
							$config['password'] = $server->database_password;
							$config['database'] = $server->database_name;
							$config['dbdriver'] = "mysql";
							$config['dbprefix'] = "";
							$config['pconnect'] = FALSE;
							$config['db_debug'] = FALSE;
							$config['cache_on'] = FALSE;
							$config['cachedir'] = "";
							$config['char_set'] = "utf8";
							$config['dbcollat'] = "utf8_general_ci";
							$config['port'] 	= 3306;
				
							$this->client_db = $this->load->database($config, TRUE);
				
							$this->client_db->where('id', $id);
							$this->client_db->update('default_cip_categories', $dataSet);
								
							$e = $this->client_db->_error_message();
							$aff = $this->client_db->affected_rows();
				
							if($e != null && $e != "") {
								$isSuccess = false;
								echo "Error";
								echo $e;
								die();	
								$oldDataSet = array(
														'name' => $category->name,
														'order_number' => $category->order_number,
														'slug'	=>url_title(strtolower(convert_accented_characters($category->name))),
														'deleted' => 0
								);
				
								$this->cip_categories_m->updateDelete($id, $oldDataSet);
				
								foreach ($servers as $server){
									$config['hostname'] = $server->domain_name;
									$config['username'] = $server->database_user;
									$config['password'] = $server->database_password;
									$config['database'] = $server->database_name;
									$config['dbdriver'] = "mysql";
									$config['dbprefix'] = "";
									$config['pconnect'] = FALSE;
									$config['db_debug'] = FALSE;
									$config['cache_on'] = FALSE;
									$config['cachedir'] = "";
									$config['char_set'] = "utf8";
									$config['dbcollat'] = "utf8_general_ci";
									$config['port'] 	= 3306;
				
									$this->client_db = $this->load->database($config, TRUE);
				
									$this->client_db->where('id', $id);
									$this->client_db->update('default_cip_categories', $oldDataSet);
								}
								break;
							}
						}
					}
				
				
				}
				else
				{
					$isSuccess = false;
				}
			}
			if(!$isSuccess){
				$this->session->set_flashdata('error', sprintf($this->lang->line('cat_edit_error'), $id));
			}else{
				$this->session->set_flashdata('success', sprintf($this->lang->line('cat_edit_success'), $deleted, $to_delete));
			}
			
		}else{
			$id_array = (!empty($id)) ? array($id) : $this->input->post('action_to');
			
			// Delete multiple
			if(!empty($id_array))
			{
				$deleted = 0;
				$to_delete = 0;
				$isSuccess = true;
				foreach ($id_array as $id) 
				{
					
					if(!$isSuccess){
						break;
					}
					$category = $this->cip_categories_m->get($id);
					$dataSet = array(
						'name' => $category->name,
						'order_number' => $category->order_number,
						'slug'	=>url_title(strtolower(convert_accented_characters($category->name))),
						'deleted' => 1
					);
					if($this->cip_categories_m->updateDelete($id, $dataSet))
					{
						$deleted++;
						$servers = $this->cip_servers_m->get_all();
						
						if($servers && count($servers)){
							foreach ($servers as $server){
								
								$config['hostname'] = $server->domain_name;
								$config['username'] = $server->database_user;
								$config['password'] = $server->database_password;
								$config['database'] = $server->database_name;
								$config['dbdriver'] = "mysql";
								$config['dbprefix'] = "";
								$config['pconnect'] = FALSE;
								$config['db_debug'] = FALSE;
								$config['cache_on'] = FALSE;
								$config['cachedir'] = "";
								$config['char_set'] = "utf8";
								$config['dbcollat'] = "utf8_general_ci";
								$config['port'] 	= 3306;
								
								$this->client_db = $this->load->database($config, TRUE);
								
								$this->client_db->where('id', $id);
								$this->client_db->update('default_cip_categories', $dataSet);
							    
							    $e = $this->client_db->_error_message();
							    $aff = $this->client_db->affected_rows();
								
								if($aff < 1) {
									$isSuccess = false;
									//echo "Error";
									//echo $e;
									
									$oldDataSet = array(
										'name' => $category->name,
										'order_number' => $category->order_number,
										'slug'	=>url_title(strtolower(convert_accented_characters($category->name))),
										'deleted' => 0
									);
		
									$this->cip_categories_m->updateDelete($id, $oldDataSet);
								
									foreach ($servers as $server){
										$config['hostname'] = $server->domain_name;
										$config['username'] = $server->database_user;
										$config['password'] = $server->database_password;
										$config['database'] = $server->database_name;
										$config['dbdriver'] = "mysql";
										$config['dbprefix'] = "";
										$config['pconnect'] = FALSE;
										$config['db_debug'] = FALSE;
										$config['cache_on'] = FALSE;
										$config['cachedir'] = "";
										$config['char_set'] = "utf8";
										$config['dbcollat'] = "utf8_general_ci";
										$config['port'] 	= 3306;
										
										$this->client_db = $this->load->database($config, TRUE);
		
										$this->client_db->where('id', $id);
										$this->client_db->update('default_cip_categories', $oldDataSet); 
									}
									break;
								}
							}
						}
						
						
					}
					else
					{
						$isSuccess = false;
					}
					$to_delete++;
				}
				
				
				if(!$isSuccess){
					$this->session->set_flashdata('error', sprintf($this->lang->line('cat_mass_delete_error'), $id));
				}else{
					$this->session->set_flashdata('success', sprintf($this->lang->line('cat_mass_delete_success'), $deleted, $to_delete));
				}
			}		
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('cat_no_select_error'));
			}
		}
		
		redirect('admin/cirpho/categories/index');
	}
	
	/**
	 * Callback method that checks the title of the category
	 * @access public
	 * @param string title The title to check
	 * @return bool
	 */
	public function _check_title($name = '')
	{
		
		if ($this->cip_categories_m->check_title($name))
		{
			$this->form_validation->set_message('_check_title', sprintf($this->lang->line('cat_already_exist_error'), $name));
			return FALSE;
		}

		return TRUE;
	}
}